// 题库页面pinia
import { defineStore } from 'pinia'
import { createCommonGetters, createCommonActions } from "../helper"
import { useSubjectStore, getParamsRequiredKeys } from "@/store"
import $api from '@/api'
export const defaultFilterObj = {
  id: "",
  typeCode: "",
  dictLabel: "全部",
  dictValue: "",
}
export const usePageQuestionListStore = defineStore('page-question-list', {
  state: () => ({

    // 所有省份
    provinceList: {
      loading: false,
      params: {},
      data: [],
      currentItem: { ...defaultFilterObj }
    },
    // 所有年级
    gradeList: {
      loading: false,
      params: {
        stage: "高中"
      },
      data: [
        { id: 1, typeCode: "", dictLabel: "高一", dictValue: 10 },
        { id: 2, typeCode: "", dictLabel: "高二", dictValue: 11 },
        { id: 3, typeCode: "", dictLabel: "高三", dictValue: 12 },
      ],
      currentItem: { id: 1, typeCode: "", dictLabel: "高一", dictValue: 10 }
    },
    // 所有年份
    yearList: {
      loading: false,
      params: {},
      data: [
        { id: "", typeCode: "", dictLabel: "全部", dictValue: "" },
        { id: 1, typeCode: "", dictLabel: 2025, dictValue: 2025 },
        { id: 2, typeCode: "", dictLabel: 2024, dictValue: 2024 },
        { id: 3, typeCode: "", dictLabel: 2023, dictValue: 2023 },
        { id: 4, typeCode: "", dictLabel: 2022, dictValue: 2022 },
      ],
      currentItem: { ...defaultFilterObj }
    },
    // 所有题型
    questionTypeList: {
      loading: false,
      params: {
        stage: "高中",
        subject: "语文"
      },
      data: [],
      currentItem: { ...defaultFilterObj }
    },

    questionList: {
      loading: false,
      params: {
        page: 1,
        size: 10,
        province: "",
        year: "",
        grade: 10,
        subject: "高中",
        snapshotId: "",
        typeId: "",
      },

    },


  }),
  getters: {
    ...createCommonGetters
  },
  actions: {
    ...createCommonActions(),
    // 重置当前项
    async resetCurrentItem() {
      this.provinceList.currentItem = { ...defaultFilterObj }
      this.gradeList.currentItem = { id: 1, typeCode: "", dictLabel: "高一", dictValue: 10 }
      this.yearList.currentItem = { ...defaultFilterObj }
      this.questionTypeList.currentItem = { ...defaultFilterObj }
    },

    // 获取题目筛选数据
    async fetchQuestionAdvancedFilter(params = {}) {
      const { dictValue: subjectName } = params

      // 并行获取所有筛选数据
      await Promise.all([
        this.fetchProvinceList(),
        this.fetchYearList(),
        this.fetchGradeList(),
        this.fetchQuestionTypeList(subjectName)
      ])
    },

    // 获取省份列表
    async fetchProvinceList() {
      try {
        if (this.isArrayEmpty("provinceList.data")) {
          this.provinceList.loading = true
          const provinces = await $api.dict.getProvince()
          if (provinces.code === 200) {
            this.provinceList.data = [defaultFilterObj, ...provinces.data]
            this.provinceList.currentItem = { ...defaultFilterObj }
          } else {
            $modal.message({ message: '【$api.dict.getProvince】接口报错，请联系管理员！', type: 'error' })
          }
        }

      } catch (error) {
        console.error('fetchProvinceList', error)
      }
    },

    // 获取年份列表
    async fetchYearList() {
      try {
        if (this.isArrayEmpty("yearList.data")) {
          const years = await $api.dict.getYear()
          if (years.code === 200) {
            this.yearList.data = [defaultFilterObj, ...years.data]
            this.yearList.currentItem = { ...defaultFilterObj }
          } else {
            $modal.message({ message: '【$api.dict.getYear】接口报错，请联系管理员！', type: 'error' })
          }

        }
      } catch (error) {
        console.error('fetchYearList', error)
      }
    },

    // 获取年级列表
    async fetchGradeList() {
      try {
        if (this.isArrayEmpty("gradeList.data")) {
          const grades = await $api.dict.getGrade({ stage: "senior" })
          if (grades.code === 200) {
            this.gradeList.data = [...grades.data]
            this.gradeList.currentItem = { id: 1, typeCode: "", dictLabel: "高一", dictValue: 10 }
          } else {
            $modal.message({ message: '【$api.dict.getGrade】接口报错，请联系管理员！', type: 'error' })
          }

        }
      } catch (error) {
        console.error('fetchGradeList', error)
      }
    },

    // 获取题型列表
    async fetchQuestionTypeList(params = {}) {
      try {
        const questionTypes = await $api.dict.getQuestionTypes({
          ...this.questionTypeList.params, ...params
        })
        if (questionTypes.code === 200) {
          this.questionTypeList.data = [defaultFilterObj, ...questionTypes.data]
          this.questionTypeList.currentItem = { ...defaultFilterObj }
        } else {
          $modal.message({ message: '【$api.dict.getQuestionTypes】接口报错，请联系管理员！', type: 'error' })
        }

      } catch (error) {
        console.error('fetchQuestionTypeList', error)
      }
    },
    // 重置列表参数
    async resetQuestionListParams() {
      this.questionList.params = {
        page: 1,
        size: 10,
        offset: 0,
        province: "",
        year: "",
        grade: this.gradeList.currentItem.dictValue,
        subject: useSubjectStore().currentItem?.dictValue,
        typeId: "",
      }
    },

    // 获取题目筛选数据
    async fetchQuestionList(params = {}) {
      try {

        let newParams = { ...this.questionList.params, ...params }
        let subParams = getParamsRequiredKeys(newParams, ["year", "grade", "typeId", "snapshotId"])

        // 创建并保存Promise
        const res = $api.question.list({ ...subParams })
        return res

      }
      catch (error) {
        console.error('fetchQuestionList', error)
      }
    },
    //重置
    reset() {
      this.$reset()
    },
  },
  persist: {
    enabled: true,
    storage: localStorage
  }

})
